// +----------------------------------------------------------------------
// | CmsHongshi [ 鸿时互娱管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.hongshihuyu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wgh <2282914052@qq.com>
// +----------------------------------------------------------------------
const Jimp = require('jimp');
module.exports = class extends think.cmswing.center {
  async __before() {
    await super.__before();
    // 判断是否登陆
    // await this.weblogin();
    if (!this.is_login) {
      // 判断浏览客户端
      if (this.isMobile) {
        // 手机端直接跳转到登录页面
        return this.redirect('/center/public/login');
      } else {
        return this.redirect('/cmswing/error/login');
      }
    }
  }
  /**
   * 账户金额管理
   * @returns {PreventPromise}
   */
  async indexAction() {
    this.tactive = 'user';
    const type = this.get('type') || 0;
    let data;
    //0:账户充值，1:提现,2:订单,3:充卡,4:充币,5:返利
    console.log('type-:'+type);
    if (type == 0) {
      data = await this.model('balance_log').where({user_id: this.user.uid}).page(this.get('page')).order('time DESC').countSelect();
    } else if (type == 1) {
      data = await this.model('profit_log').alias('a').where({user_id:this.user.uid}).field('a.id,a.user_id,a.proxy_id,a.type,a.amount,a.amount_log,a.note,a.status,a.settle_time,a.create_time as time,a.origin_id').page(this.get('page')).order('create_time DESC').countSelect();
    } else if (type == 2) {
      data = await this.model('withdraw').alias('a').where({user_id:this.user.uid}).field('a.id,a.user_id,a.amount,a.payment,a.pay_code,a.realname,a.bankno,a.bankname,a.wxno,a.alipayno,a.status,a.create_time as time,a.accept_time,a.withdraw_time,a.withdraw_no').page(this.get('page')).order('create_time DESC').countSelect();
      for (const val of data.data) {
        val.channel = await this.model('pingxx').where({id: val.payment}).getField('title', true);
      }
    }

    const html = this.pagination(data);
    // think.log(data);
    this.assign('pagination', html);
    this.assign('list', data.data);
    this.assign('type', type);
    this.assign('count', data.count);
    // 获取用户信息
    const userInfo = await this.model('member').find(this.user.uid);
    this.assign('userInfo', userInfo);
    // 未付款的充值订单统计
    const unpaid = await this.model('order').where({
      user_id: this.user.uid,
      type: 1,
      is_del: 0,
      pay_status: 0
    }).count('id');
    this.assign('unpaid', unpaid);
    this.meta_title = '账户管理';
    
    //console.log('保留4位小数--:'+numberformat(10.00015,4,'','','floor'));
    // 判断浏览客户端
    if (this.isMobile) {
      if (this.isAjax('get')) {
        for (const v of data.data) {
          v.time = this.moment(v.create_time).format('YYYY-MM-DD HH:mm:ss');
          //v.amount = v.amount==0.00?0.00:formatCurrency(v.amount);
          //v.amount_log = v.amount_log==0.00?0.00:formatCurrency(v.amount_log);
        }
        return this.json(data);
      } else {
        this.active = 'user/index';
        return this.display(this.mtpl());
      }
    } else {
      return this.display();
    }
  }

  /**
   * 充值
   */
  async rechargeAction() {
    if (this.isAjax('POST')) {
      const data = this.post();
      if (think.isEmpty(data.order_amount)) {
        return this.fail('请输入金额！');
      } else if (!think.isNumberString(data.order_amount)) {
        return this.fail('金额类型错误！');
      } else if (think.isEmpty(data.payment)) {
        return this.fail('必须选一种支付方式！');
      }

      // 用户
      data.user_id = this.user.uid;
      // 生成订单编号//todo
      // let nowtime = new Date().valueOf();
      // let oid = ["c", this.user.uid, nowtime]
      console.log('this.user.uid-:'+this.user.uid);
//      data.order_no = await this.model('order').orderid(this.user.uid);
      data.order_no = await this.model('cmswing/order').orderid(this.user.uid,'02');
      console.log('data.order_no-:'+data.order_no);
      // 支付状态 pay_stayus 0:未付款 ,1:已付款
      data.pay_status = 0;
      // 订单状态 status 2:等待审核，3:已审核
      data.status = 2;
      // 发货状态 type 0:普通，1:充值
      data.type = 1;
      // 订单创建时间 create_time
      data.create_time = new Date().valueOf();
      // 生成订单
      const parter = this.config('setup.KAIRUI_APP_ID');// '1884'
	  const key = this.config('setup.KAIRUI_LIVE_SECRET_KEY');//'bb3cb208045c4a289c305e4cc7d1d7db'
	  const serverUrl = this.config('setup.KAIRUI_SERVER_URL');// 'http://g.788xw.com/bank/'
	  const callbackUrl = this.config('setup.KAIRUI_CALLBACK_URL');//'http://www.hongshihuyu.com/center/pay/payres'
	  const hrefbackUrl = this.config('setup.KAIRUI_HREFBACK_URL');//'http://www.hongshihuyu.com/center/account'
	  const channel = await this.model('pingxx').where({id:data.payment}).getField('channel', true);//'6001'
      
	  var money=data.order_amount;
      var orderId=data.order_no;
//      var payerIp=this.ip();
      var payerIp='';
      var attach = '';
      for (var i = 0; i < 8; i++) {
    	  attach += Math.floor(Math.random() * 10);
      }
      var signStr='parter='+parter+'&type='+channel+'&value='+money+'&orderid='+orderId+'&callbackurl='+callbackUrl+key;
      signStr=think.md5(signStr);
      data.parter=parter;
      data.channel=channel;
      data.money=money;
      data.orderId=orderId;
      data.callbackurl=callbackUrl;
      data.hrefbackurl=hrefbackUrl;
      data.key=key;
      data.serverUrl=serverUrl;
      data.payerIp=payerIp;
      data.attach =attach;
      data.sign = signStr;

      if (signStr) {
        // 把存到订单
        const order_id = await this.model('order').add(data);

        // 支付日志
        const receiving = {
          order_id: order_id,
          user_id: this.user.uid,
          amount: data.order_amount,
          create_time: new Date().getTime(),
          payment_time: new Date().getTime(),
          doc_type: 1,
          payment_id: data.payment,
          pay_status: 0
        };
        await this.model('doc_receiving').add(receiving);
        return this.success({name: '支付订单对接成功，正在转跳！', data: data});
      } else {
        return this.fail('调用接口失败！');
      }
      // think.log(data);
    } else {
      // ping++ 支付渠道 pc网页
      // 根据不同的客户端调用不同的支付方式
      let map;
      if (this.isMobile) {
        map = {
          type: 2,
          status: 1,
          agent:'kairui'
        };
        if (!this.isweixin) {
          map.channel = ['!=', 'wx_pub'];
        }
      } else {
        map = {
          type: 1,
          status: 1
        };
      }
      const paylist = await this.model('pingxx').where(map).order('sort ASC').select();
      this.assign('paylist', paylist);
      this.meta_title = '充值';
      if (this.isMobile) {
        this.active = 'user/index';
        return this.display(this.mtpl());
      } else {
        this.display();
      }
    }
  }
  
  /**
   * 提现
   */
  async withdrawAction() {
    if (this.isAjax('POST')) {
      const data = this.post();
      if (think.isEmpty(data.amount)) {
        return this.fail('请输入提现金额！');
      } else if (!think.isNumberString(data.amount)) {
        return this.fail('提现金额类型错误！');
      } else if (think.isEmpty(data.payment)) {
        return this.fail('必须选一种提现方式！');
      }

      // 用户
      data.user_id = this.user.uid;
      console.log('data.user_id-:'+data.user_id);
      data.withdraw_no = await this.model('cmswing/order').orderid(this.user.uid,'08');
      console.log('data.withdraw_no-:'+data.withdraw_no);
      // 状态  0 待确认，1 打款中  2 已打款
      data.status = 0;
      // 创建时间 create_time
      data.create_time = new Date().valueOf();

      const withdraw_id = await this.model('withdraw').add(data);
      if (withdraw_id) {
    	  const update = await this.model('member').where({id:data.user_id}).decrement('amount', data.amount);
    	  if (update) {
    		  return this.success({name:'申请提现成功！'});
    	  }else{
    		  await this.model('withdraw').where({id:withdraw_id}).delete();
    		  return this.fail('申请提现失败！');
    	  }
    	  // 支付日志
//        const receiving = {
//          order_id: withdraw_id,
//          user_id: this.user.uid,
//          amount: data.amount,
//          create_time: new Date().getTime(),
//          doc_type: 1,
//          payment_id: data.payment,
//          pay_status: 0,
//          note:`${await get_nickname(this.user.uid)} 发起提现,提现编号：${data.withdraw_no}`
//        };
//        await this.model('doc_receiving').add(receiving);
      } else {
        return this.fail('申请提现失败！');
      }
      // think.log(data);
    } else {
      // ping++ 支付渠道 pc网页
      // 根据不同的客户端调用不同的支付方式
      let map = {
          type: 3,
          status: 1,
          agent:'withdraw'
       };
      
      const withdrawlist = await this.model('pingxx').where(map).order('sort ASC').select();
      this.assign('withdrawlist', withdrawlist);
      const withdraw_min_amount = this.config('setup.WITHDRAW_MIN_AMOUNT');//
      this.assign('withdraw_min_amount', withdraw_min_amount);
      const userInfo = await this.model('member').find(this.user.uid);
      this.assign('amount', userInfo.amount);
      this.meta_title = '申请提现';
      if (this.isMobile) {
        this.active = 'center/account';
        return this.display(this.mtpl());
      } else {
        this.display();
      }
    }
  }
  
//  async rechargeAction() {
//	    if (this.isAjax('POST')) {
//	      const data = this.post();
//	      if (think.isEmpty(data.order_amount)) {
//	        return this.fail('请输入金额！');
//	      } else if (!think.isNumberString(data.order_amount)) {
//	        return this.fail('金额类型错误！');
//	      } else if (think.isEmpty(data.payment)) {
//	        return this.fail('必须选一种支付方式！');
//	      }
//
//	      // 用户
//	      data.user_id = this.user.uid;
//	      // 生成订单编号//todo
//	      // let nowtime = new Date().valueOf();
//	      // let oid = ["c", this.user.uid, nowtime]
//	      console.log('this.user.uid-:'+this.user.uid);
////	      data.order_no = await this.model('order').orderid(this.user.uid);
//	      data.order_no = await this.model('cmswing/order').orderid(this.user.uid);
//	      console.log('data.order_no-:'+data.order_no);
//	      // 支付状态 pay_stayus 0:未付款 ,1:已付款
//	      data.pay_status = 0;
//	      // 订单状态 status 2:等待审核，3:已审核
//	      data.status = 2;
//	      // 发货状态 type 0:普通，1:充值
//	      data.type = 1;
//	      // 订单创建时间 create_time
//	      data.create_time = new Date().valueOf();
//	      // 生成订单
//
//	      // 判断是否已经绑定pingxx_id,如果已绑定查询pingxx订单直接支付。防止订单重复生成。
//	      // console.log(111111111)
//	      // 获取渠道
//	      const channel = await this.model('pingxx').where({id: data.payment}).getField('channel', true);
//	      let open_id;
//	      if (channel == 'wx_pub') {
//	        open_id = await this.session('wx_openid');
//	      }
//	      // 调用ping++ 服务端
//	      const payment = this.service('cmswing/payment', this.ctx);
//	      // 传入 channel,order_no,order_amount,this.ip()
//	      const ip = think.env === 'development' ? '127.0.0.1' : this.ip;
//	      const charges = await payment.pingxx(channel, data.order_no, data.order_amount, ip, open_id);
//	      // console.log(charges);
//	      if (charges) {
//	        // 把pingxx_id存到订单
//	        data.pingxx_id = charges.id;
//	        const order_id = await this.model('order').add(data);
//
//	        // 支付日志
//	        const receiving = {
//	          order_id: order_id,
//	          user_id: this.user.uid,
//	          amount: data.order_amount,
//	          create_time: new Date().getTime(),
//	          payment_time: new Date().getTime(),
//	          doc_type: 1,
//	          payment_id: data.payment,
//	          pay_status: 0
//	        };
//	        await this.model('doc_receiving').add(receiving);
//	        return this.success({name: '支付订单对接成功，正在转跳！', data: charges});
//	      } else {
//	        return this.fail('调用接口失败！');
//	      }
//	      // think.log(data);
//	    } else {
//	      // ping++ 支付渠道 pc网页
//	      // 根据不同的客户端调用不同的支付方式
//	      let map;
//	      if (this.isMobile) {
//	        map = {
//	          type: 2,
//	          status: 1
//	        };
//	        if (!this.isweixin) {
//	          map.channel = ['!=', 'wx_pub'];
//	        }
//	      } else {
//	        map = {
//	          type: 1,
//	          status: 1
//	        };
//	      }
//	      const paylist = await this.model('pingxx').where(map).order('sort ASC').select();
//	      this.assign('paylist', paylist);
//	      this.meta_title = '充值';
//	      console.log('111111111111-:'+this.isMobile);
//	      if (this.isMobile) {
//	    	  console.log('22222222222222-:'+this.isMobile);
//	        this.active = 'user/index';
//	        return this.display(this.mtpl());
//	      } else {
//	        this.display();
//	      }
//	    }
//	  }
};
